﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac.Integration.Web;
using Autofac.Integration.Web.Mvc;
using Autofac;
using System.Reflection;
using MyNote.Data;
using MyNote.Models;
using System.Security.Principal;
using MyNote.Data.Models;
using System.Threading;
using MyNote.FullText;

namespace MyNote
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication, IContainerProviderAccessor
    {
        public static class Constants
        {
            public static string PENDING_CREATE_NOTE = "PENDING_CREATE_NOTE";
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "NotePager", // Route name
                "{controller}/{action}/{num}",
                new { controller = "Home", action = "Index", num = UrlParameter.Optional }
            );

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
        }
        private static IndexWorker _indexWorker;

        public static IndexWorker FullTextIndexer
        {
            get { return _indexWorker; }
        }

        private FullTextIndexContainer _fullTextDatabase;

        protected void Application_Start()
        {
            RegisterIoc();

            AreaRegistration.RegisterAllAreas();
            this.BeginRequest += Application_BeginRequest;

            // _indexWorker = new IndexWorker(Server.MapPath("/ftindex/"));
            _fullTextDatabase = new FullTextIndexContainer();
            _indexWorker = new IndexWorker(new DbDirectory(_fullTextDatabase));
            StartFullTextIndexer();

            RegisterRoutes(RouteTable.Routes);
        }

        private void StartFullTextIndexer()
        {
            var context = new NoteModelContainer();
            ThreadPool.QueueUserWorkItem(_indexWorker.CreateIndexThread, context);
            ThreadPool.QueueUserWorkItem(_indexWorker.UpdateIndexThread);
        }

        private void RegisterIoc()
        {
            var builder = new ContainerBuilder();

            var assembly = Assembly.GetExecutingAssembly();
            builder.RegisterControllers(assembly);
            builder.RegisterModelBinders(assembly);
            builder.Register<IPrincipal>(c => HttpContext.Current.User).ExternallyOwned();

            _containerProvider = new ContainerProvider(builder.Build());

            ControllerBuilder.Current.SetControllerFactory(
                new AutofacControllerFactory(ContainerProvider));
        }

        private static IContainerProvider _containerProvider;

        public IContainerProvider ContainerProvider
        {
            get { return _containerProvider; }
        }

        protected void Application_End()
        {
            _indexWorker.StopIndexThreads();
            _fullTextDatabase.SaveChanges();
            _fullTextDatabase.Connection.Close();
            _fullTextDatabase = null;
        }

        protected void Application_BeginRequest(object sender, EventArgs e) 
        {
            var encoding = Request.Form["_charset_"];
            if (!string.IsNullOrEmpty(encoding))
                Request.ContentEncoding = System.Text.Encoding.GetEncoding(encoding);
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            Session.Add("wl_Session_started", true);
        } 
    }
}